/*
     File: ImageScrollView.m
 Abstract: Centers image within the scroll view and configures image sizing and display.
  Version: 1.1
 
 Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple
 Inc. ("Apple") in consideration of your agreement to the following
 terms, and your use, installation, modification or redistribution of
 this Apple software constitutes acceptance of these terms.  If you do
 not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and
 subject to these terms, Apple grants you a personal, non-exclusive
 license, under Apple's copyrights in this original Apple software (the
 "Apple Software"), to use, reproduce, modify and redistribute the Apple
 Software, with or without modifications, in source and/or binary forms;
 provided that if you redistribute the Apple Software in its entirety and
 without modifications, you must retain this notice and the following
 text and disclaimers in all such redistributions of the Apple Software.
 Neither the name, trademarks, service marks or logos of Apple Inc. may
 be used to endorse or promote products derived from the Apple Software
 without specific prior written permission from Apple.  Except as
 expressly stated in this notice, no other rights or licenses, express or
 implied, are granted by Apple herein, including but not limited to any
 patent rights that may be infringed by your derivative works or by other
 works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 
 Copyright (C) 2010 Apple Inc. All Rights Reserved.
 
 */

#import "MapScrollView.h"

@implementation MapScrollView

@synthesize drawingView;
@synthesize tokenView;
@synthesize zoomGesture;
@synthesize backgroundView;
@synthesize playingActivated;
@synthesize gridView;
@synthesize objectView;
@synthesize suspensionCount;

- (void)dealloc {
    [backgroundView release];
    backgroundView = nil;
    [drawingView release];
    drawingView = nil;
	[gridView release];
    gridView = nil;
    [objectView release];
    objectView = nil;
    [tokenView release];
    tokenView = nil;
    [zoomGesture release];
    zoomGesture = nil;
    [super dealloc];
}

- (void)awakeFromNib {
	self.delegate = self;
	self.showsVerticalScrollIndicator = NO;
	self.showsHorizontalScrollIndicator = NO;
	self.bounces = YES;
	self.bouncesZoom = YES;
	self.decelerationRate = UIScrollViewDecelerationRateFast;
	self.scrollEnabled = NO;
	self.multipleTouchEnabled = YES;
	self.autoresizesSubviews = YES;
	self.playingActivated = NO;
}

#pragma mark -
#pragma mark Configure scrollView to display new image (tiled or not)

- (void)displayTiledMap:(Map *)map withTileSize:(CGSize)tileSize withScale:(int)scale{
    // clear the previous imageView
    [backgroundView removeFromSuperview];
    [backgroundView release];
	[drawingView removeFromSuperview];
	[drawingView release];
	[gridView removeFromSuperview];
	[gridView release];
	[tokenView removeFromSuperview];
	[tokenView release];
    [objectView removeFromSuperview];
	[objectView release];
    backgroundView = nil;
	drawingView = nil;
	gridView = nil;
	tokenView = nil;
    objectView = nil;
    
    // make a new view
    backgroundView = [[BackgroundView alloc] initWithMap:map withTileSize:tileSize withScale:scale];
	drawingView = [[DrawingView alloc] initWithMap:map withTileSize:tileSize withScale:scale];
	gridView = [[GridView alloc] initWithMap:map withTileSize:tileSize withScale:scale];
	tokenView = [[TokenView alloc] initWithMap:map withTileSize:tileSize withScale:scale];
    objectView = [[TokenView alloc] initWithMap:map withTileSize:tileSize withScale:scale];
    gridView.annotates = YES;
	backgroundView.scale = 3.0;
	drawingView.scale = 3.0;
	gridView.scale = 3.0;
	tokenView.scale = 3.0;
    objectView.scale = 3.0;
	[self addSubview:backgroundView];
	[self addSubview:drawingView];
    [self addSubview:objectView];
    [self addSubview:gridView];
	[self addSubview:tokenView];
    [self centerView];
    self.contentSize = map.size;
}	

#pragma mark -
#pragma mark Methods called during rotation to preserve the zoomScale and the visible portion of the image

// returns the center point, in image coordinate space, to try to restore after rotation. 
- (CGPoint)pointToCenterAfterRotation {
    CGPoint boundsCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    return [self convertPoint:boundsCenter toView:backgroundView];
}

- (CGPoint)maximumContentOffset {
    CGSize contentSize = self.contentSize;
    CGSize boundsSize = self.bounds.size;
    return CGPointMake(contentSize.width - boundsSize.width, contentSize.height - boundsSize.height);
}

- (CGPoint)minimumContentOffset {
    return CGPointZero;
}

// Adjusts content offset and scale to try to preserve the old zoomscale and center.
- (void)restoreCenterPoint:(CGPoint)oldCenter scale:(CGFloat)oldScale {    
    // Step 1: restore zoom scale, first making sure it is within the allowable range.
    self.zoomScale = MIN(self.maximumZoomScale, MAX(self.minimumZoomScale, oldScale));
    
    
    // Step 2: restore center point, first making sure it is within the allowable range.
    
    // 2a: convert our desired center point back to our own coordinate space
    CGPoint boundsCenter = [self convertPoint:oldCenter fromView:backgroundView];
    // 2b: calculate the content offset that would yield that center point
    CGPoint offset = CGPointMake(boundsCenter.x - self.bounds.size.width / 2.0, 
                                 boundsCenter.y - self.bounds.size.height / 2.0);
    // 2c: restore offset, adjusted to be within the allowable range
    CGPoint maxOffset = [self maximumContentOffset];
    CGPoint minOffset = [self minimumContentOffset];
    offset.x = MAX(minOffset.x, MIN(maxOffset.x, offset.x));
    offset.y = MAX(minOffset.y, MIN(maxOffset.y, offset.y));
    self.contentOffset = offset;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
	return nil;
}

#pragma mark -
#pragma mark New scrolling methods
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	fingerCount += [touches count];
	if (fingerCount > 2) {
		fingerCount = 2;
	}
	if (fingerCount > 1) {
		dragging = YES;
	}
	if ([touches count] < 2) {
		if (![Players sharedLocalPlayer].currentlyMovingToken && !tokenView.addTokensIsActivated &&!backgroundView.backgroundActivated &&!playingActivated && !objectView.addObjectsIsActivated && !backgroundView.changeAllBackgroundActivated) {
			[drawingView touchesBegan:touches withEvent:event];
		} else if (backgroundView.backgroundActivated) {
			[backgroundView touchesBegan:touches withEvent:event];
		}
        if (objectView.addObjectsIsActivated) {
            [objectView touchesBegan:touches withEvent:event];
        } else if (!backgroundView.backgroundActivated && ![LoadedImages sharedLoadedImages].drawingActivated) {
			[tokenView touchesBegan:touches withEvent:event];
		}
	}
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	if ([touches count] > 1 && [touches count] < 3) {
		zoomGesture.enabled = NO;
		UITouch *touch = [touches anyObject];
		CGPoint oldPoint = [touch previousLocationInView:self];
		CGPoint newPoint = [touch locationInView:self];
		CGPoint offset = self.contentOffset;
		offset.x += ((oldPoint.x - newPoint.x) * 2); 
		offset.y += ((oldPoint.y - newPoint.y) * 2);
		if (offset.x < [self minimumContentOffset].x) {
			offset.x = [self minimumContentOffset].x;
		} else if (offset.x > [self maximumContentOffset].x) {
			offset.x = [self maximumContentOffset].x;
		}
		if (offset.y < [self minimumContentOffset].y) {
			offset.y = [self minimumContentOffset].y;
		} else if (offset.y > [self maximumContentOffset].y) {
			offset.y = [self maximumContentOffset].y;
		}
		[self setContentOffset:offset animated:NO];
		[drawingView.map cancelCurrentPaths];
		for (UITouch *touch in touches) {
			CGPoint gridCoords = [drawingView convertCoordsToGridCoords:[touch locationInView:self]];
			[drawingView setNeedsDisplayInRect:CGRectMake((gridCoords.x - 1)*drawingView.tileSize.width, (gridCoords.y - 1)*drawingView.tileSize.height, drawingView.tileSize.width * 3, drawingView.tileSize.height * 3)];
		}
		[tokenView touchesMoved:touches withEvent:event];
        [objectView touchesMoved:touches withEvent:event];
	} else if (fingerCount <= 1 && !dragging) {
		
		if (![Players sharedLocalPlayer].currentlyMovingToken && !tokenView.addTokensIsActivated && !backgroundView.backgroundActivated && !playingActivated && !objectView.addObjectsIsActivated && !backgroundView.changeAllBackgroundActivated) {
			[drawingView touchesMoved:touches withEvent:event];
		} else if (backgroundView.backgroundActivated) {
			[backgroundView touchesMoved:touches withEvent:event];
		}
        if (objectView.addObjectsIsActivated) {
            [objectView touchesMoved:touches withEvent:event];
        } else if (!backgroundView.backgroundActivated && ![LoadedImages sharedLoadedImages].drawingActivated) {
			[tokenView touchesMoved:touches withEvent:event];
		}
		//[backgroundView touchesMoved:touches withEvent:event];
	}
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	fingerCount -= [touches count];
	if (fingerCount < 1) {
		if ([touches count] < 2 && !dragging) {
			if (![Players sharedLocalPlayer].currentlyMovingToken && !tokenView.addTokensIsActivated && !backgroundView.backgroundActivated && !playingActivated && !objectView.addObjectsIsActivated && !backgroundView.changeAllBackgroundActivated) {
				[drawingView touchesEnded:touches withEvent:event];
			} else if (backgroundView.backgroundActivated) {
				[backgroundView touchesEnded:touches withEvent:event];
			} else if (objectView.addObjectsIsActivated) {
                [objectView touchesEnded:touches withEvent:event];
            } else {
				[tokenView touchesEnded:touches withEvent:event];
			}
		}
		dragging = NO;
		fingerCount = 0;
		zoomGesture.enabled = YES;
	}
}

- (void)centerView {
	CGPoint offset = self.contentOffset;
	offset.x = drawingView.map.size.width/2;
	offset.y = drawingView.map.size.height/2;
	[self setContentOffset:offset animated:NO];
	
}

- (void)activateScroll {
	fingerCount = 0;
	dragging = NO;
	zoomGesture.enabled = YES;
}

- (void)disableUI {
    dimmingViewOutlet.alpha = 0.3;
    dimmingViewOutlet.hidden = NO;
    [workInProgressView startAnimating];
}

- (void)enableUI {
    dimmingViewOutlet.alpha = 0.0;
    [workInProgressView stopAnimating];
}

@end
